sample() function to create the numbers.
library(dplyr)
fancy_matrix <-
sample(1:1000, 8*8, replace = TRUE) %>%
matrix(nrow = 8, ncol = 8)
fancy_matrix
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
## [1,] 731 896 825 343 633 303 850 674
## [2,] 891 602 970 399 369 362 406 219
## [3,] 210 348 750 47 973 400 95 699
## [4,] 207 225 136 15 589 351 57 682
## [5,] 642 767 927 102 140 52 628 66
## [6,] 587 550 886 316 421 70 848 208
## [7,] 447 492 222 428 311 803 834 863
## [8,] 600 388 197 506 32 716 697 966
terra::rast() function can be fed with matrices to create a raster layer.
library(terra)
fancy_raster_layer <-
terra::rast(fancy_matrix)
terra::plot(fancy_raster_layer)
The raster() function can not only be used to create raster data on the fly, which is also not very interesting. Instead, we can use it to import already prepared data.
.tiff files in the ./data/ folder of the workshop directory (repository).
getwd(). Setting is done with setwd().
immigrants_cologne <-
terra::rast("./data/immigrants_cologne.tif")
+ and - operators.
# load all layers
immigrants_cologne <-
terra::rast("./data/immigrants_cologne.tif")
germans_cologne <-
terra::rast("./data/germans_cologne.tif")
inhabitants_cologne <-
terra::rast("./data/inhabitants_cologne.tif")
# create sum layer
immigrants_germans_sum <-
immigrants_cologne + germans_cologne
# create difference layer
difference_layer <-
inhabitants_cologne - immigrants_germans_sum
difference_layer
## class : SpatRaster
## dimensions : 289, 264, 1 (nrow, ncol, nlyr)
## resolution : 100, 100 (x, y)
## extent : 4094850, 4121250, 3084050, 3112950 (xmin, xmax, ymin, ymax)
## coord. ref. : ETRS89-extended / LAEA Europe (with axis order normalized for visualization)
## source : memory
## name : inhabitants_cologne
## min value : -2
## max value : 0
# get a summary statistic
summary(difference_layer)
## Length Class Mode
## 1 SpatRaster S4
# create a table of counts
difference_layer %>%
as.data.frame() %>%
table()
## inhabitants_cologne
## -2 -1 0
## 11 2052 11711